package cn.kgc.ssm.controller;

import cn.hutool.captcha.LineCaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 课工场
 * @date 2024/3/4
 * @description 生成验证码图片
 */
@Controller
@RequestMapping("captcha")
public class CaptchaController {


    @GetMapping
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {

        // 获取生成验证码图片的对象
        LineCaptcha lineCaptcha = new LineCaptcha(120, 40, 4, 3);
        // 获取的验证码     1.响应给前端页面  图片   1234   2. 保存验证码在服务中
        String code = lineCaptcha.getCode();
        HttpSession session = request.getSession();
        session.setAttribute("code", code);

        // 响应给前端页面  图片
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
